package com.soda.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.soda.bean.User;
import com.soda.service.UserService;
import com.soda.service.impl.UserServiceImpl;

public class LoginServlet extends HttpServlet {

	UserService us=new UserServiceImpl();
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String param = request.getParameter("param");
		if (param != null) {
			// 登录
			if ("login".equals(param)) {// 判断登录
				login(request, response);// 调用登录函数
			}
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

	/*
	 * 登录验证，如果登录成功，则把需要的信息保存到session中
	 */
	public void login(HttpServletRequest request, HttpServletResponse response)
			throws IOException {

		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		// 获取登录表单参数
		String loginname = request.getParameter("loginname");
		String password = request.getParameter("password");
		//String yanzheng=request.getParameter("yanzheng");
		
		//String code=request.getSession().getAttribute("code").toString();
		
	/*	if(!code.equalsIgnoreCase(yanzheng)){
			
			out.print("<script>alert('验证码错误！');window.location.href='houtai/login.jsp';</script>");
			return;
		}*/
		
		User user = us.login(loginname);

		if (user != null) {
			if (user.getUsePassWord().equals(password)) {
				if (user.getUseDelete() == 0) {

					out.print("<script>alert('对不起！该用户已被删除！');window.location.href='houtai/login.jsp';</script>");
					return;
				} else if (user.getUseState() == 0) {

					out.print("<script>alert('对不起！该用户已被禁用！');window.location.href='houtai/login.jsp';</script>");
					return;
				} else if (user.getRole().getRolState() == 0) {
					out.print("<script>alert('对不起！该角色已被禁用！');window.location.href='houtai/login.jsp';</script>");
				} else if (user.getRole().getRolDelete() == 0) {
					out.print("<script>alert('对不起！该角色已被删除！');window.location.href='houtai/login.jsp';</script>");
				} else {
					request.getSession().setAttribute("user", user);
					response.sendRedirect(request.getContextPath()
							+ "/houtai/main.jsp");
					return;
				}
			} else {

				out.print("<script>alert('用户名或密码错误~');window.location.href='houtai/login.jsp';</script>");
				return;
			}
		} else {
			out.print("<script>alert('对不起！该用户不存在！');window.location.href='houtai/login.jsp';</script>");
			return;
		}

	}

}
